package others;

import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;

public class CompletableFutureLearn {
    public static void main(String[] args) {
//        CompletableFuture<Machina> cf = CompletableFuture.completedFuture(new Machina());
//        CompletableFuture<Machina> cf2 = cf.thenApply(Machina::work);
//        CompletableFuture<Machina> cf3 = cf2.thenApply(Machina::work);
//        CompletableFuture<Machina> cf4 = cf3.thenApply(Machina::work);
        //回调 thenApply() 一旦开始一个操作，在完成所有任务之前，不会完成 CompletableFuture 的构建。虽然这有时很有用，
        // 但是开始所有任务通常更有价值，这样就可以运行继续前进并执行其他操作。我们可通过thenApplyAsync() 来实现此目的：



        CompletableFuture<Machina> cf = CompletableFuture.completedFuture(new Machina())
                .thenApplyAsync(Machina::work)
                .thenApplyAsync(Machina::work)
                .thenApplyAsync(Machina::work);
        System.out.println(cf.join());
        //thenApply和thenApplyAsync都是顺序执行，不同的是thenApply需要先执行完成任务才会返回创建完成future对象
    }
}

class Machina {
    private static final AtomicInteger atomicInteger = new AtomicInteger(0);

    public static Machina work(Machina m) {
        if (Objects.equals(atomicInteger.incrementAndGet(), 3)) {
            System.out.println("end");
        } else {
            System.out.println("cur integer:" + atomicInteger.get());
        }
        return m;
    }

}
